package com.ssn.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectTest
{
	public Object copy(Object object) throws Exception
	{
		Class<?> classType = object.getClass();
		// Constructor cons = classType.getConstructor(new Class[] {
		// String.class,
		// int.class });
		// Object obj = cons.newInstance(new Object[] { "hello", 1 });

		Object objectCopy = classType.getConstructor(new Class[] {})
				.newInstance(new Object[] {});
		Field[] fields = classType.getDeclaredFields();
		for (Field field : fields)
		{
			String name = field.getName();
			String firstLetter = name.substring(0, 1).toUpperCase();
			String getMethodName = "get" + firstLetter
					+ name.substring(1, name.length());
			String setMethodName = "set" + firstLetter
					+ name.substring(1, name.length());
			Method getMethod = classType.getMethod(getMethodName,
					new Class[] {});
			Method setMethod = classType.getMethod(setMethodName,
					new Class[] { field.getType() });

			Object value = getMethod.invoke(object, new Object[] {});
			setMethod.invoke(objectCopy, new Object[] { value });
		}

		return objectCopy;
	}

	public static void main(String[] args) throws Exception
	{
		Customer customer=new Customer("Tom", 20);
		customer.setId(1L);
		
		ReflectTest test = new ReflectTest();
		Customer customer2=(Customer) test.copy(customer);
		
		System.out.println(customer2.getId() + customer2.getAge() + customer2.getName());
	}
}

class Customer
{
	private long id;
	private String name;
	private int age;

	public Customer()
	{

	}

	public Customer(String name, int age)
	{
		this.name = name;
		this.age = age;
	}

	public long getId()
	{
		return id;
	}

	public void setId(long id)
	{
		this.id = id;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public int getAge()
	{
		return age;
	}

	public void setAge(int age)
	{
		this.age = age;
	}

}
